package com.lh_travel.lohas.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lh_travel.lohas.R;
import com.lh_travel.lohas.adapter.AdViewPagerAdapter;
import com.lh_travel.lohas.adapter.CommonAdapter;
import com.lh_travel.lohas.adapter.ViewHolder;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.CalendarBean;
import com.lh_travel.lohas.domain.DafultMessageEvent;
import com.lh_travel.lohas.domain.calendarDate;
import com.lh_travel.lohas.utils.DateTimeUtil;
import com.lh_travel.lohas.widget.HeadGridView;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by aaron on 2018/6/11.
 */

public class CalendarActivity extends baseActivity {

    private boolean mutil;
    private int count = 1;
    private ArrayList<View> fouceList = new ArrayList<>();

    private ViewPager vp_calendar;
    private int gril_week;
    private int selectYear;
    private int selectMonth;
    private int currentYear;
    private int curentMonth;
    private TextView tv_currentdate;
    private ImageButton img_right;
    private ImageButton img_left;
    private List<View> viewList = null;
    private ImageButton img_back;
    private Button img_clear;
    CommonAdapter dateAdapter;
    private Map<Integer, CalendarBean> dateMap;

    private String currentDate;
    private TextView tv_checkin_date;
    private TextView tv_checkin_week;
    private TextView tv_checkout_date;
    private TextView tv_checkout_week;
    private String checkin;
    private String checkout;
    private TextView tv_count;
    private Button btn_confirm;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_calendar);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    public void findView() {

        vp_calendar = (ViewPager) findViewById(R.id.vp_calendar);
        tv_currentdate = (TextView) findViewById(R.id.tv_currentdate);
        img_left = (ImageButton) findViewById(R.id.img_left);
        img_right = (ImageButton) findViewById(R.id.img_right);
        img_back = (ImageButton) findViewById(R.id.img_back);
        img_clear = (Button) findViewById(R.id.img_clear);
        tv_checkin_date = (TextView) findViewById(R.id.tv_checkin_date);
        tv_checkin_week = (TextView) findViewById(R.id.tv_checkin_week);
        tv_checkout_date = (TextView) findViewById(R.id.tv_checkout_date);
        tv_checkout_week = (TextView) findViewById(R.id.tv_checkout_week);
        tv_count = (TextView) findViewById(R.id.tv_count);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
    }

    @Override
    public void bindListner() {

        img_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentItem = vp_calendar.getCurrentItem();
                vp_calendar.setCurrentItem(--currentItem);
            }
        });

        img_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentItem = vp_calendar.getCurrentItem();
                vp_calendar.setCurrentItem(++currentItem);
            }
        });

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        img_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count = 1;

                for (int i = 0; i < fouceList.size(); i++) {

                    RelativeLayout view = (RelativeLayout) fouceList.get(i);

                    TextView tv_shape = view.findViewById(R.id.tv_shape);

                    tv_shape.setVisibility(View.GONE);

                }

                if (mutil) {

                    String date = DateTimeUtil.getCurrentMonthCH();

                    checkin = date;
                    checkout = DateTimeUtil.addDate(checkin, 1);

                    tv_checkin_date.setText(checkin.substring(5));
                    tv_checkout_date.setText(checkout.substring(5));

                    tv_checkin_week.setText(DateTimeUtil.CHGetWeek(checkin));
                    tv_checkout_week.setText(DateTimeUtil.CHGetWeek(checkout));

                    tv_count.setText("共" + DateTimeUtil.getTwoDayInterval(checkout, checkin) + "晚");

                } else {

                    try {
                        checkout = DateTimeUtil.addDate(DateTimeUtil.anyStrToStr(checkin, "yyyy-mm-dd", "yyyy年mm月dd日"), 1);
                        tv_checkout_date.setText(checkout.substring(5));
                        tv_checkout_week.setText(DateTimeUtil.CHGetWeek(checkout));

                        tv_count.setText("共" + DateTimeUtil.getTwoDayInterval(checkout, DateTimeUtil.anyStrToStr(checkin, "yyyy-mm-dd", "yyyy年mm月dd日")) + "日");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (count == 3) {

                    DafultMessageEvent dafultMessageEvent = new DafultMessageEvent();

                    dafultMessageEvent.TAG = "CalendarActivity";

                    try {

                        if (mutil) {

                            dafultMessageEvent.checkin = DateTimeUtil.strTostr(checkin);


                        } else {

                            dafultMessageEvent.checkin = checkin;

                        }

                        dafultMessageEvent.checkout = DateTimeUtil.strTostr(checkout);

                        EventBus.getDefault().post(dafultMessageEvent);

                        finish();

                    } catch (Exception e) {
                        e.printStackTrace();

                        finish();
                    }

                } else {

                    showMessage("请输入正确的时间");
                }

            }
        });

    }

    @Override
    public void ensureUI() {

        //从上层获取传递的数据,是单选还是多选

        mutil = getIntent().getBooleanExtra("mutil", false);

        checkin = getIntent().getStringExtra("checkIn");

        checkout = getIntent().getStringExtra("checkOut");

        setSupportActionBar(toolbar);
        toolbar.setEnabled(true);

        tv_count.setText("共" + DateTimeUtil.anyGetTwoDayInterval(checkout, checkin, "yyyy-mm-dd") + "晚");

        setVpContent();

    }

    private void setVpContent() {

        viewList = new ArrayList<>();
        dateMap = new HashMap<>();

        String date = DateTimeUtil.getCurrentMonth();

        int year = Integer.valueOf(date.substring(0, 4));

        int month = Integer.valueOf(date.substring(4, 6));

        int day = Integer.valueOf(date.substring(6));

        if (checkin != null) {

            tv_checkin_week.setText(checkin);

            try {
                tv_checkin_date.setText(DateTimeUtil.anyStrToStr(checkin, "yyyy-mm-dd", "yyyy年mm月dd日").substring(5));
                tv_checkout_date.setText(DateTimeUtil.anyStrToStr(checkout, "yyyy-mm-dd", "yyyy年mm月dd日").substring(5));

                tv_checkin_week.setText(DateTimeUtil.GetWeek(checkin, "yyyy-mm-dd"));
                tv_checkout_week.setText(DateTimeUtil.GetWeek(checkout, "yyyy-mm-dd"));

                tv_count.setText("共" + DateTimeUtil.anyGetTwoDayInterval(checkout, checkin, "yyyy年mm月dd日") + "晚");

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {

            checkin = year + "年" + month + "月" + day + "日";
            checkout = DateTimeUtil.addDate(checkin, 1);

            tv_checkin_date.setText(checkin.substring(5));
            tv_checkout_date.setText(checkout.substring(5));

            tv_checkin_week.setText(DateTimeUtil.CHGetWeek(checkin));
            tv_checkout_week.setText(DateTimeUtil.CHGetWeek(checkout));

            tv_count.setText("共" + DateTimeUtil.getTwoDayInterval(checkout, checkin) + "晚");
        }

        selectYear = year;
        selectMonth = month;

        currentYear = year;
        curentMonth = month;

        tv_currentdate.setText(currentYear + "年" + curentMonth + "月");

        for (int i = 0; i < 10; i++) {

            HeadGridView gridview;

            View inflate = View.inflate(mContext, R.layout.grid_calendar, null);

            gridview = inflate.findViewById(R.id.gridview);

            gril_week = getWeek(selectYear, selectMonth, 1);

            if (i == 0) {

                //今天的index;
                final int today = (day + gril_week - 1);

                CalendarBean bean = getDateList(selectYear, selectMonth, day);

                dateMap.put(i, bean);

                dateAdapter = new CommonAdapter<calendarDate>(mContext, bean.dateList, R.layout.item_grid_calendar) {
                    @Override
                    public void convert(ViewHolder helper, calendarDate item, int position) {

                        helper.setText(R.id.tv_date, item.date + "");
                        helper.setViewEnable(R.id.tv_date, item.check);
                        helper.setViewEnable(R.id.rl_main, item.check);

                        if (position == today) {

                            helper.setText(R.id.tv_date, "今");
                            helper.setTextColorAndSize(R.id.tv_date, Color.parseColor("#fc8261"), 20);

                        }
                    }
                };

            } else {

                CalendarBean bean = getDateList(selectYear, selectMonth, 0);

                dateMap.put(i, bean);

                dateAdapter = new CommonAdapter<calendarDate>(mContext, bean.dateList, R.layout.item_grid_calendar) {
                    @Override
                    public void convert(ViewHolder helper, calendarDate item, int position) {

                        helper.setText(R.id.tv_date, item.date + "");
                        helper.setViewEnable(R.id.tv_date, item.check);
                        helper.setViewEnable(R.id.rl_main, item.check);
                    }
                };
            }

            gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //用tag来判断是不是操作同一个日期,用count来判断是第几次

                    if (dateMap.get(vp_calendar.getCurrentItem()).dateList.get(position).check) {

                        if (mutil) {

                            if (count == 1) {

                                RelativeLayout rl_main = (RelativeLayout) view;

                                TextView tv_shape = rl_main.findViewById(R.id.tv_shape);

                                tv_shape.setText("入");

                                tv_shape.setVisibility(View.VISIBLE);

                                fouceList.add(rl_main);

                                count = 2;

                                String cMonth = curentMonth + "";
                                String cDay = dateMap.get(vp_calendar.getCurrentItem()).dateList.get(position).date + "";

                                currentDate = currentYear + "年" + (cMonth.length() > 1 ? cMonth : "0" + cMonth) + "月" + (cDay.length() > 1 ? cDay : "0" + cDay) + "日";

                                checkin = currentDate;

                                tv_checkin_date.setText(currentDate.substring(5));
                                tv_checkin_week.setText(DateTimeUtil.CHGetWeek(currentDate));

                            } else if (count == 2) {

                                String cMonth = curentMonth + "";
                                String cDay = dateMap.get(vp_calendar.getCurrentItem()).dateList.get(position).date + "";

                                String selctDate = currentYear + "年" + (cMonth.length() > 1 ? cMonth : "0" + cMonth) + "月" + (cDay.length() > 1 ? cDay : "0" + cDay) + "日";

                                if (DateTimeUtil.getTwoDayInterval(selctDate, currentDate) <= 0) {

                                    showMessage("请选择正确的时间");

                                } else {

                                    checkout = selctDate;

                                    RelativeLayout rl_main = (RelativeLayout) view;

                                    TextView tv_shape = rl_main.findViewById(R.id.tv_shape);

                                    tv_shape.setText("离");

                                    tv_shape.setVisibility(View.VISIBLE);

                                    tv_checkout_date.setText(checkout.substring(5));
                                    tv_checkout_week.setText(DateTimeUtil.CHGetWeek(checkout));

                                    tv_count.setText("共" + DateTimeUtil.getTwoDayInterval(checkout, checkin) + "晚");

                                    fouceList.add(rl_main);

                                    count = 3;
                                }
                            } else {


                            }

                        } else if (count != 3) {

                            String cMonth = curentMonth + "";
                            String cDay = dateMap.get(vp_calendar.getCurrentItem()).dateList.get(position).date + "";

                            String selctDate = currentYear + "年" + (cMonth.length() > 1 ? cMonth : "0" + cMonth) + "月" + (cDay.length() > 1 ? cDay : "0" + cDay) + "日";

                            try {
                                if (DateTimeUtil.getTwoDayInterval(selctDate, DateTimeUtil.anyStrToStr(checkin, "yyyy-mm-dd", "yyyy年mm月dd日")) <= 0) {

                                    showMessage("请选择正确的时间");

                                } else {

                                    count = 3;

                                    checkout = selctDate;

                                    RelativeLayout rl_main = (RelativeLayout) view;

                                    TextView tv_shape = rl_main.findViewById(R.id.tv_shape);

                                    tv_shape.setText("离");

                                    tv_shape.setVisibility(View.VISIBLE);

                                    tv_checkout_date.setText(checkout.substring(5));
                                    tv_checkout_week.setText(DateTimeUtil.CHGetWeek(checkout));

                                    tv_count.setText("共" + DateTimeUtil.getTwoDayInterval(checkout, DateTimeUtil.anyStrToStr(checkin, "yyyy-mm-dd", "yyyy年mm月dd日")) + "晚");

                                    fouceList.add(rl_main);

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                }
            });

            gridview.setAdapter(dateAdapter);

            viewList.add(inflate);

            if (month == 12) {

                selectYear = selectYear + 1;
                selectMonth = 1;

            } else {

                selectMonth++;

            }
        }

        AdViewPagerAdapter pageAdapter = new AdViewPagerAdapter(viewList);

        vp_calendar.setAdapter(pageAdapter);
        vp_calendar.setOffscreenPageLimit(viewList.size());

        vp_calendar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            private int currentPosition = 0;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position > currentPosition) {
                    //右滑

                    currentPosition = position;

                    if (curentMonth != 12) {
                        curentMonth++;

                    } else {

                        currentYear++;
                        curentMonth = 1;
                    }

                } else if (position < currentPosition) {
                    //左滑
                    if (curentMonth != 1) {
                        curentMonth--;

                    } else {

                        currentYear--;
                        curentMonth = 12;
                    }

                    currentPosition = position;
                }

                tv_currentdate.setText(currentYear + "年" + curentMonth + "月");
            }

            @Override
            public void onPageSelected(int position) {

                if (position == 0) {
                    img_left.setVisibility(View.GONE);

                } else if (position == viewList.size() - 1) {

                    img_right.setVisibility(View.GONE);

                } else {

                    img_left.setVisibility(View.VISIBLE);
                    img_right.setVisibility(View.VISIBLE);

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private CalendarBean getDateList(int year, int month, int day) {

        int lastDay = 0;

        CalendarBean calendarBean = new CalendarBean();

        ArrayList<calendarDate> arrayList = new ArrayList<>();

        //获取第一天是星期几
        int week = getWeek(year, month, 1);

        //假如不是星期天
        if (week != 0) {

            //获取上个月最后一天

            if (month == 1) {

                lastDay = DateTimeUtil.getMonthLastDay(year - 1, 12);

            } else {

                lastDay = DateTimeUtil.getMonthLastDay(year, month - 1);

            }

            //把上个月的天数添加到日历数组中
            for (int i = week; i > 0; i--) {

                arrayList.add(new calendarDate(lastDay - i + 1, false));
            }

            calendarBean.lastMonth = arrayList.size() - 1 + "";
        }

        //把当月的天数加到日历数组中
        int count = DateTimeUtil.getMonthLastDay(year, month);

        for (int i = 1; i <= count; i++) {

            if (day > 0) {

                if (i < day) {

                    arrayList.add(new calendarDate(i, false));

                } else {
                    arrayList.add(new calendarDate(i, true));
                }

            } else {

                arrayList.add(new calendarDate(i, true));

            }
        }

        calendarBean.nextMonth = arrayList.size() + "";

        //把下个月也添加到日历数组中

        int nextMonth = 42 - week - count;

        for (int i = 1; i <= nextMonth; i++) {

            arrayList.add(new calendarDate(i, false));

        }

        calendarBean.dateList = arrayList;

        return calendarBean;
    }

    private int getWeek(int year, int month, int day) {
        int week = 0;

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        String str = year + "-" + month + "-" + day;

        try {
            Date d = dateFormat.parse(str);
            c.setTime(d);
            week = c.get(Calendar.DAY_OF_WEEK) - 1;

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return week;
    }

}
